<template>
  <div class="order-detail whiteBox" style="padding-top: 0">
    <el-button icon="el-icon-plus" type="text" size="small" @click="addOperationShow = true; ruleForm.fileList = []">{{ $t('common.add') }}</el-button>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column :label="$t('common.fileName')" prop="fileName" />
      <el-table-column :label="$t('common.date')" prop="createTime" />
      <el-table-column :label="$t('common.operation')">
        <template slot-scope="scope">
          <el-tag size="medium" type="success" style="margin-right: 10px" @click="viewImg(scope.row.filePath, scope.row, scope.$index)">
            <i class="el-icon-view" />
            {{ $t('common.view') }}
          </el-tag>
          <el-tag size="medium" @click="downLoad(scope.row.filePath, scope.row.fileName)">
            <i class="el-icon-download" />
            {{ $t('common.download') }}
          </el-tag>
          <el-button type="danger" size="mini" style="margin-left: 10px;" @click="handleDelete(scope.row, scope.$index)">
            {{ $t('common.del') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="$t('common.add')" :visible.sync="addOperationShow" width="60%">
      <UploadList v-model="ruleForm.fileList" :limit="8" :params="{serviceType: 'IN_WAREHOUSE', serviceId: ruleForm.id}" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="addOperationShow = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="addOperation">{{ $t('common.confirm') }}</el-button>
      </span>
    </el-dialog>
    <el-image-viewer v-if="dialogViewFileImg" :on-close="closeViewer" :url-list="viewerImgList" :z-index="19940306" />
    <Pdf ref="viewPdf" :url="previewUrl" />
    <el-dialog :visible.sync="txtVisible"  :title="''" >
      <div>{{ previewUrl }}</div>
      <iframe :src="previewUrl" frameborder="0" width="100%" height="600"></iframe>
    </el-dialog>
 </div>
</template>
<script>
import dayjs from 'dayjs'
import Pdf from '@/components/Pdf/index.vue'
import TableComponent from '@/components/Table/list.vue'
import FormComponents from '@/components/FormComponents/index.vue'
// import UploadList from '@/components/Upload/common/uploadList.vue'
import UploadList from '@/components/FileUpload/index.vue'
import ElImageViewer from '@/components/ElImageViewer/index.vue'
import { baseFileList, addBaseFile, addBaseFileBatch, clearCacheKey } from '@/api/common'
export default {
    /* 
      serviceType: 表单类型
      入库 IN_WAREHOUSE
      出库 OUT_WAREHOUSE
      订单 ORDER
      serviceId: 表单id
    */
  props: ['serviceType', 'serviceId'],
  components: { TableComponent, FormComponents, UploadList, ElImageViewer, Pdf },
  data() {
    return {
      ruleForm: {
        serviceId: null,
        serviceType: null,
        fileList: []
      },
      addOperationShow: false,
      ruleForm_column: [{ prop: 'fileList', slot: 'fileList', label: this.$t('common.files'), type: 'input', col: 24 }],
      tableData: [],
      dialogViewFileImg: false,
      viewerImgList: [],
      previewUrl: null,
      txtVisible: false
    }
  },
  methods: {
    returnData(data) {
      if (data.list) {
        data.list.map(r => {
          r.value = JSON.parse(r.value)
        })
        return data.list
      }
    },
    addOperation() {
      this.addOperationShow = false
      // const params = {
      //   serviceId: this.serviceId,
      //   serviceType: this.serviceType,
      //   fileName: this.ruleForm.fileList[0].name,
      //   filePath: this.ruleForm.fileList[0].url
      // }
      const params = this.ruleForm.fileList.map(r=> ({
        ...r,
        serviceId: this.serviceId,
        serviceType: this.serviceType,
      }))
      // console.log('params', params)
      // return
      addBaseFileBatch(params).then(res => {
        if (res) {
          this.$message.success(this.$t('common.succcessInfo'))
          this.addOperationShow = false
          this.getList()
        }
      })
    },
    delOperation() {},
    getList() {
      this.search = ''
      baseFileList({ serviceId: this.serviceId, serviceType: this.serviceType, pageNum: 1, pageSize: 10 }).then(r => {
        r.content.map(a => {
          a.createTime = dayjs(a.createTime).format('YYYY-MM-DD HH:mm:ss')
        })
        this.tableData = r.content
      })
    },
    // 判断是图片后缀名
    isImage(url) {
      if (typeof url === 'string') {
        const fileType = url.substring(url.lastIndexOf('.')).toLowerCase()
        return ['.jpg', '.png', '.jpeg', '.gif', '.webp', 'ico'].includes(fileType)
      }
      return false
    },
    isPdf(url) {
      const fileExtension = url.split('.').pop().toLowerCase();
      if(fileExtension === 'pdf') {
        return true
      }
    },
    isTxt(url) {
      const fileExtension = url.split('.').pop().toLowerCase();
      if(fileExtension === 'txt') {
        return true
      }
    },
    /* 查看附件 */
    viewImg(url, item, index) {
      if (this.isImage(url) || item.isimage) {
        this.dialogViewFileImg = true
        this.viewerImgList = [url]
      } 
      // 暂时不放 等待后再议
      // else if(this.isPdf(url)) {
      //   this.preview(url)
      // } else if(this.isTxt(url)) {
      //   this.previewUrl = url;
      //   this.txtVisible = true
      // } 
      else {
        window.open('https://view.officeapps.live.com/op/view.aspx?src=' + url, '_blank')
      }
    },
    /* 下载附件 */
    downLoad(url, name) {
      var link = document.createElement('a')
      link.style.display = 'none'
      link.href = url.replace('ossm.ejet.com', 'ejet-manager.oss-cn-hangzhou.aliyuncs.com')
      link.setAttribute('download', name)
      document.body.appendChild(link)
      link.click()
    },
    // pdfY预览
    // 后端返回二进制流
    preview(url) {
      this.previewUrl = url;
      this.$refs.viewPdf.open()
    },
    // 关闭查看图片
    closeViewer() {
      this.dialogViewFileImg = false
    },
    // 删除附件
    handleDelete(row, index) {
      this.$confirm(this.$t('common.confirmMsg') + '?', this.$t('common.reminder'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: "warning",
      })
        .then(() => {
          const id = row.id
          clearCacheKey(id).then(res=>{
            if(res) {
              this.$message({
                type: 'success',
                message: this.$t('common.succcessInfo')
              });
              this.tableData.splice(index, 1)
              this.getList()
            }
          });
        })
        .catch(() => {});
    }
  }
}
</script>
